package it.asvp.asvp_portal.data.dao.impl;


import it.asvp.asvp_portal.data.dao.MemberDao;
import it.asvp.asvp_portal.data.entity.member.Member;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository
public class MemberDaoImpl implements MemberDao{

	private static final Log log = LogFactory.getLog(MemberDaoImpl.class);

	@Autowired
	SessionFactory sessionFactory;
	
	public Long persist(Member transientInstance) {
		log.debug("persisting Member instance");
		Long id;
		try {
			id=(Long) sessionFactory.getCurrentSession().save(transientInstance);
			log.debug("persist successful");
		} catch (RuntimeException re) {
			log.error("persist failed", re);
			throw re;
		}
		return id;
	}

	public void delete(Member persistentInstance) {
		log.debug("deleting Member instance");
		try {
			sessionFactory.getCurrentSession().delete(persistentInstance);
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}

	public Member merge(Member detachedInstance) {
		log.debug("merging Member instance");
		try {
			Member result = (Member)sessionFactory.getCurrentSession().merge(
					detachedInstance);
			log.debug("merge successful");
			return result;
		} catch (RuntimeException re) {
			log.error("merge failed", re);
			throw re;
		}
	}

	public Member findById(java.lang.Long id) {
		
		Criteria cr=sessionFactory.getCurrentSession().createCriteria(Member.class);
		cr.add(Restrictions.eq("id", id));
		Member m = (Member)cr.uniqueResult();
		return m;
	}
	
    public Member findByEmail(String email) {
		
		Criteria cr=sessionFactory.getCurrentSession().createCriteria(Member.class);
		cr.add(Restrictions.eq("email", email));
		Member m = (Member)cr.uniqueResult();
		return m;
	}

	public Member findByFiscalCode(String fiscalCode) {
		
		Criteria cr=sessionFactory.getCurrentSession().createCriteria(Member.class);
		cr.add(Restrictions.eq("fiscalCode", fiscalCode));
		Member m = (Member)cr.uniqueResult();
		return m;
	}

	 
	@SuppressWarnings("unchecked")
	public List<Member> selectAll() {
		
		Criteria cr=sessionFactory.getCurrentSession().createCriteria(Member.class);
		List<Member> list=(List<Member>)cr.list();
		return list;
	}

	

}
